package com.rf.richfitwheel.admin.sys.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rf.richfitwheel.admin.feignclient.FWfTaskService;
import com.rf.richfitwheel.admin.sys.dao.*;
import com.rf.richfitwheel.admin.sys.model.*;
import com.rf.richfitwheel.admin.sys.model.Dictionary;
import com.rf.richfitwheel.admin.sys.service.*;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.R;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.common.utils.UuidUtil;
import com.rf.richfitwheel.workflow.conf.WorkflowContants;
import com.rf.richfitwheel.workflow.entity.WfTaskParam;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class BusTypServiceImpl implements BusTypService {

    private static Logger logger = LoggerFactory.getLogger(BusTypServiceImpl.class);

    @Autowired
    private BusTypMapper busTypMapper;
    @Autowired
    private SysBankMapper sysBankMapper;

    @Autowired
    private AttTypMapper attTypMapper;
    @Autowired
    private SxOpinionMapper sxOpinionMapper;

    @Autowired
    private FWfTaskService fWfTaskService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private StationService stationService;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private SysMsgStreamService msgStreamService;
    //sys_dictionary
    @Autowired
    private  DictionaryMapper dictionaryMapper;

    public PageUtils queryPage(Map<String, Object> params) {
        JSONObject jsonObject = JSONObject.fromObject(params.get("dataForm"));
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Object> page = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        BusTypExample busTypExample = new BusTypExample();
        BusTypExample.Criteria criteria = busTypExample.createCriteria();
        //业务编码
        if (StringUtils.isNotBlank(jsonObject.get("busno"))) {
            criteria.andBusnoLike("%" + jsonObject.getString("busno") + "%");
        }
        //业务名称
        if (StringUtils.isNotBlank(jsonObject.get("busnm"))) {
            criteria.andBusnmLike("%" + jsonObject.getString("busnm") + "%");
        }
        //业务名称
        if (StringUtils.isNotBlank(jsonObject.get("bustyp"))) {
            criteria.andBustypLike("%" + jsonObject.getString("bustyp") + "%");
        }
        busTypExample.setOrderByClause("busno asc");
        List<BusTyp> list = busTypMapper.selectByExample(busTypExample);
        pageUtils.setList(page.getResult());
        pageUtils.setTotalCount((int) page.getTotal());
        return pageUtils;
    }

    @Override
    public void addBusTyp(BusTyp busTyp, UserVO user) {
        busTyp.setId(UuidUtil.get32UUID());
        busTypMapper.insert(busTyp);
    }

    @Override
    public void updateBusTypData(Map<String, Object> params, UserVO user) {
        JSONObject jsonObject = JSONObject.fromObject(params);
        BusTyp busTyp = (BusTyp) JSONObject.toBean(jsonObject.getJSONObject("busTyp"), BusTyp.class);
        //附件管理
        JSONArray attTypDataList = JSONArray.fromObject(params.get("attTypDataList"));

        busTypMapper.updateByPrimaryKeySelective(busTyp);
        this.deleteAttByBusno(busTyp.getBusno());

        //附件管理
        for (int i = 0; i < attTypDataList.size(); i++) {
            JSONObject attTypData = attTypDataList.getJSONObject(i);
            AttTyp attTyp = new AttTyp();
            attTyp.setId(UuidUtil.get32UUID());
            attTyp.setAttno(attTypData.getString("attno"));
            attTyp.setAttnm(attTypData.getString("attnm"));
            attTyp.setAttsnm(attTypData.getString("attsnm"));
            attTyp.setAttmust(attTypData.getString("attmust"));
            attTyp.setAttidx(i + 1);
            attTyp.setAttst(attTypData.getString("attst"));
            attTyp.setAttpage(attTypData.getString("attpage"));
            attTyp.setModuletype(busTyp.getBustyp());
            attTyp.setBusno(busTyp.getBusno());
            attTypMapper.insert(attTyp);
        }
    }

    @Override
    public void saveBusTyp(Map<String, Object> params, UserVO user) {
        BusTyp busTyp = (BusTyp) JSONObject.toBean(JSONObject.fromObject(params.get("busTyp")), BusTyp.class);
        this.addBusTyp(busTyp, user);
        //附件管理
        JSONArray attTypDataList = JSONArray.fromObject(params.get("attTypDataList"));
        for (int i = 0; i < attTypDataList.size(); i++) {
            JSONObject attTypData = attTypDataList.getJSONObject(i);
            AttTyp attTyp = new AttTyp();
            attTyp.setId(UuidUtil.get32UUID());
            attTyp.setAttno(attTypData.getString("attno"));
            attTyp.setAttnm(attTypData.getString("attnm"));
            attTyp.setAttsnm(attTypData.getString("attsnm"));
            attTyp.setAttmust(attTypData.getString("attmust"));
            attTyp.setAttidx(i + 1);
            attTyp.setAttst(attTypData.getString("attst"));
            attTyp.setAttpage(attTypData.getString("attpage"));
            attTyp.setModuletype(busTyp.getBustyp());
            attTyp.setBusno(busTyp.getBusno());
            attTypMapper.insert(attTyp);
        }
    }

    @Override
    public BusTyp selectByBusno(String busno) {
        BusTypExample busTypExample = new BusTypExample();
        BusTypExample.Criteria criteria = busTypExample.createCriteria();
        criteria.andBusnoEqualTo(busno);
        List<BusTyp> list = busTypMapper.selectByExample(busTypExample);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void deleteBusTyp(String id) {
        busTypMapper.deleteByPrimaryKey(id);
    }

    @Override
    public BusTyp selectById(String id) {
        return busTypMapper.selectByPrimaryKey(id);
    }


    @Override
    public List<AttTyp> getListByBusno(String busno) {
        AttTypExample example = new AttTypExample();
        AttTypExample.Criteria criteria = example.createCriteria();
        criteria.andBusnoEqualTo(busno);
        example.setOrderByClause("attidx");
        List<AttTyp> attTyp = attTypMapper.selectByExample(example);
        return attTyp;
    }

    @Override
    public void deleteAttByBusno(String busno) {
        List<AttTyp> attTyps = this.getListByBusno(busno);
        for (AttTyp attTyp : attTyps) {
            attTypMapper.deleteByPrimaryKey(attTyp.getId());
        }
    }

    @Override
    public void saveSxOpinion(Map<String, Object> params, UserVO user) {
        SxOpinion sxOpinion = JSONUtil.toBean(JSONUtil.parseObj(params.get("sxOpinion")), SxOpinion.class);
        Org parentOrg = user.getDefaultOrg().getParentOrg();
        Org grandpa = user.getDefaultOrg().getGrandpa();
        if (grandpa != null) {
            sxOpinion.setOrgcode(grandpa.getOrgCode());
            sxOpinion.setOrgname(grandpa.getOrgName());
        } else {
            sxOpinion.setOrgcode(parentOrg.getOrgCode());
            sxOpinion.setOrgname(parentOrg.getOrgName());
        }
        sxOpinion.setId(UuidUtil.get32UUID());
        sxOpinion.setTellername(user.getStaffName());
        sxOpinion.setOperator(user.getStaffName());
        sxOpinion.setOperatordate(new Date());
        sxOpinion.setCreatedate(new Date());
        sxOpinion.setCreatenm(user.getStaffName());
        if (sxOpinion.getMoudletypeList() != null && !sxOpinion.getMoudletypeList().isEmpty()) {
            sxOpinion.setMoudletype(org.apache.commons.lang.StringUtils.join(sxOpinion.getMoudletypeList(), "/"));
        }
        sxOpinionMapper.insert(sxOpinion);

        WfTaskParam wfTaskParam = (WfTaskParam) JSONObject.toBean(JSONObject.fromObject(params.get("wfTaskParam")), WfTaskParam.class);
        wfTaskParam.setUserVO(user);
        wfTaskParam.setProcessInsName("意见审批");
        wfTaskParam.setBusinessKey(sxOpinion.getId());//业务主键
        wfTaskParam.setApproveNo("意见审批");//审批编号
        Map<String, Object> variables = wfTaskParam.getBaseParam(user);//组装流程参数
        wfTaskParam.setVariables(variables);
        R r = fWfTaskService.submitTask(wfTaskParam);
        if (!"0".equals(r.get("code").toString())) {
            throw new BusinessException(r.get("msg").toString());
        }
    }

    @Override
    public void modifySxOpinion(String id, String status, String processInstanceId) {
        SxOpinion sxOpinion = sxOpinionMapper.selectByPrimaryKey(id);
        if (status.equals(WorkflowContants.PROCESS_STATUS_1)) {
            sxOpinion.setApvst("2");
            sxOpinion.setProcessInstanceId(processInstanceId);
            sxOpinionMapper.updateByPrimaryKeySelective(sxOpinion);
        }
        //这里判断是否是开立申请的流程结束
        if (status.equals(WorkflowContants.PROCESS_STATUS_2)) {
            //4本部审批结束
            sxOpinion.setApvst("3");
            sxOpinionMapper.updateByPrimaryKeySelective(sxOpinion);
            //审批完成给司库管理中心发送信息
            sendSiKuMessage("", "有新的意见反馈,请查看处理.");
        }
        if (status.equals(WorkflowContants.PROCESS_STATUS_3)) {
            //6终止
            sxOpinion.setApvst("6");
            sxOpinionMapper.updateByPrimaryKeySelective(sxOpinion);
        }
    }

    @Override
    public void updateSxOpinion(Map<String, Object> params, UserVO user) {
        SxOpinion sxOpinion = JSONUtil.toBean(JSONUtil.parseObj(params.get("sxOpinion")), SxOpinion.class);
        sxOpinion.setOperator(user.getStaffName());
        sxOpinion.setOperatordate(new Date());
        if (sxOpinion.getMoudletypeList() != null && !sxOpinion.getMoudletypeList().isEmpty()) {
            sxOpinion.setMoudletype(org.apache.commons.lang.StringUtils.join(sxOpinion.getMoudletypeList(), "/"));
        }
        sxOpinionMapper.updateByPrimaryKey(sxOpinion);
        WfTaskParam wfTaskParam = (WfTaskParam) JSONObject.toBean(JSONObject.fromObject(params.get("wfTaskParam")), WfTaskParam.class);
        Map<String, Object> variables = wfTaskParam.getVariables();//组装流程参数
        wfTaskParam.setVariables(variables);
        wfTaskParam.setUserVO(user);
        wfTaskParam.setProcessInsName("首页意见审批");
        fWfTaskService.submitTask(wfTaskParam);
    }

    @Override
    public SxOpinion findSxOpinion(String id) {
        SxOpinion sxOpinion = sxOpinionMapper.selectByPrimaryKey(id);
//        if (StringUtils.isNotBlank(sxOpinion.getMoudletype())) {
//            sxOpinion.setMoudletypeList(Arrays.asList(sxOpinion.getMoudletype().split("/")));
//        }
        if (StringUtils.isNotBlank(sxOpinion.getMoudletype())) {
            List<List<String>> objects = new ArrayList<>();
            String[] split = sxOpinion.getMoudletype().split("/");
            for (int i = 0; i < split.length; i++) {
                String s = split[i].replaceAll("\"\"", "");
                List<String> list1 = JSON.parseArray(s, String.class);
                objects.add(list1);
            }
            sxOpinion.setMoudletypeLists(objects);
        }
        return sxOpinion;
    }

    @Override
    public PageUtils querySxOpinionPage(Map<String, Object> params) {
        JSONObject jsonObject = JSONObject.fromObject(params.get("dataForm"));
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Object> page = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        SxOpinionExample sxOpinionExample = new SxOpinionExample();
        SxOpinionExample.Criteria criteria = sxOpinionExample.createCriteria();
        //业务编码
        if (StringUtils.isNotBlank(jsonObject.get("orgCode"))) {
            criteria.andOrgcodeEqualTo("%" + jsonObject.getString("orgCode") + "%");
        }
        //单位名称
        if (StringUtils.isNotBlank(jsonObject.get("orgName"))) {
            criteria.andOrgnameLike("%" + jsonObject.getString("orgName") + "%");
        } else {
            UserVO user = UserUtil.getUser();
            Org parentOrg = user.getDefaultOrg().getParentOrg();
            Org grandpa = user.getDefaultOrg().getGrandpa();
            if (user.getStaffName().equals("超级管理员") || grandpa.getOrgName().contains("司库")) {
            } else {
                criteria.andOrgnameEqualTo(grandpa.getOrgName());
            }
        }
        //业务名称
        if (StringUtils.isNotBlank(jsonObject.get("moudleType"))) {
            criteria.andMoudletypeLike("%" + jsonObject.getString("moudleType") + "%");
        }
        //意见状态
        if (StringUtils.isNotBlank(jsonObject.get("apvst")) && (!"1".equals(jsonObject.getString("apvst")))) {
            criteria.andApvstEqualTo(jsonObject.getString("apvst"));
        }
        sxOpinionExample.setOrderByClause("operatordate desc");
        List<SxOpinion> list = sxOpinionMapper.selectByExample(sxOpinionExample);
        for (SxOpinion sxOpinion : list) {
           if (StringUtils.isNotBlank(sxOpinion.getMoudletype())) {
               sxOpinion.setMoudletypeList(Arrays.asList(sxOpinion.getMoudletype().split("/")));
           }
//            if (StringUtils.isNotBlank(sxOpinion.getMoudletype())) {
//                List<List<String>> objects = new ArrayList<>();
//                String[] split = sxOpinion.getMoudletype().split("/");
//                for (int i = 0; i < split.length; i++) {
//                    String s = split[i].replaceAll("\"\"", "");
//                    List<String> list1 = JSON.parseArray(s, String.class);
//                    objects.add(list1);
//                }
//                sxOpinion.setMoudletypeLists(objects);
//            }
        }
        pageUtils.setList(page.getResult());
        pageUtils.setTotalCount((int) page.getTotal());
        return pageUtils;
    }

    //给司库管理中心发送消息
    public void sendSiKuMessage(String orgCode, String message) {
        Org byName = null;
        if (StringUtils.isBlank(orgCode)) {
            byName = findByName();
        } else {
            byName = findByName(orgCode);
        }
        String code = "";
        if (byName != null) {
            code = byName.getOrgCode();
        }
        if (!code.equals("")) {
            List<User> guarantee = getStartUser(code, "guarantee");
            if (guarantee != null && !guarantee.isEmpty()) {
                for (User user : guarantee) {
                    HashMap<String, Object> hashMap = new HashMap<>();
                    //{"senderId":发送用户id,"pageParam":页面参数,"msgCode":消息定义编码,"businessId":业务id,"msgContext":消息内容,"msgContextParam":消息内容参数}
                    hashMap.put("senderId", "1");
                    hashMap.put("pageParam", null);
                    hashMap.put("msgCode", "NYSGXKG");
                    hashMap.put("businessId", null);
                    hashMap.put("receiverId", user.getId());
//                    hashMap.put("msgContext", "有新的意见反馈,请查看.");
                    hashMap.put("msgContext", message);
                    hashMap.put("msgContextParam", null);
                    try {
                        msgStreamService.sendMsg(hashMap);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }

        }
    }

    //查找司库管理中心的的机构信息
    private Org findByName() {
        OrgExample orgExample = new OrgExample();
        OrgExample.Criteria criteria = orgExample.createCriteria();
        criteria.andOrgNameLike("%" + "司库管理" + "%");
        criteria.andOrgTypeEqualTo("2");
        criteria.andOrgRankEqualTo("1");
        Org org = orgMapper.selectByExample(orgExample).stream().findFirst().orElse(null);
        return org;
    }

    //根据单位编号查询部门下的用户信息
    private List<User> getStartUser(String orgCode, String moduleType) {
        List<User> users = new ArrayList<>();
        HashMap<String, Object> params = new HashMap<>();
        params.put("orgCode", orgCode);
        List<Org> orgList = orgService.findOrgDeptList(params);
        if (!orgList.isEmpty()) {
            for (Org org : orgList) {
                if (!org.getOrgType().equals("1") && !org.getOrgRank().equals("1")) {
                    List<Station> stations = stationService.getStationsByOrgId(org.getId(), "guarantee");
                    if (stations != null && !stations.isEmpty()) {
                        for (Station station : stations) {
                            try {
                                List<User> allUserByStationIds = sysUserService.getAllUserByStationIds(station.getId());
                                users.addAll(allUserByStationIds);
                            } catch (Exception e) {
                                new BusinessException("为查询到用户信息");
                            }
                        }
                    }
                }
            }
        }
        return users.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<User>(Comparator.comparing(User::getId))), ArrayList::new));
    }


    @Override
    public void updateSxOpinionOne(SxOpinion sxOpinion, UserVO user) {
        sxOpinionMapper.updateByPrimaryKey(sxOpinion);
        sendSiKuMessage(sxOpinion.getOrgcode(), sxOpinion.getOrgname() + "提交的意见反馈已经处理完成,请在反馈台账中查看结果.");
    }

    //查找司库管理中心的的机构信息
    private Org findByName(String orgCode) {
        OrgExample orgExample = new OrgExample();
        OrgExample.Criteria criteria = orgExample.createCriteria();
        criteria.andOrgCodeLike("%" + orgCode + "%");
        criteria.andOrgTypeEqualTo("2");
        criteria.andOrgRankEqualTo("1");
        Org org = orgMapper.selectByExample(orgExample).stream().findFirst().orElse(null);
        return org;
    }

    @Override
    public PageUtils querySysBankPage(Map<String, Object> params) {
        JSONObject jsonObject = JSONObject.fromObject(params.get("dataForm"));
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Object> page = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        SysBankExample sysBankExample = new SysBankExample();
        SysBankExample.Criteria criteria = sysBankExample.createCriteria();
        //联行号
        if (StringUtils.isNotBlank(jsonObject.get("unitCode"))) {
            criteria.andUnitCodeLike("%" + jsonObject.getString("unitCode") + "%");
        }
        //联行名称
        if (StringUtils.isNotBlank(jsonObject.get("unitName"))) {
            criteria.andUnitNameLike("%" + jsonObject.getString("unitName") + "%");
        }
        //银行名称
        if (StringUtils.isNotBlank(jsonObject.get("unitBank"))) {
            criteria.andUnitBankLike("%" + jsonObject.getString("unitBank") + "%");
        }
        //省份
        if (StringUtils.isNotBlank(jsonObject.get("unitProvince"))) {
            criteria.andUnitProvinceLike("%" + jsonObject.getString("unitProvince") + "%");
        }
        //地区/市
        if (StringUtils.isNotBlank(jsonObject.get("unitCity"))) {
            criteria.andUnitCityLike("%" + jsonObject.getString("unitCity") + "%");
        }
        if (StringUtils.isNotBlank(jsonObject.get("unitType"))) {
            criteria.andUnitTypeEqualTo(jsonObject.getString("unitType"));
        }
        if (StringUtils.isNotBlank(jsonObject.get("unitWord"))) {
            criteria.andUnitWordLike("%" + jsonObject.getString("unitWord") + "%");
        }
        sysBankExample.setOrderByClause("unit_code desc");
        List<SysBank> list = sysBankMapper.selectByExample(sysBankExample);
        pageUtils.setList(page.getResult());
        pageUtils.setTotalCount((int) page.getTotal());
        return pageUtils;
    }

    @Override
    public R saveBankOne(SysBank sysBank) {
        SysBankExample sysBankExample = new SysBankExample();
        SysBankExample.Criteria criteria = sysBankExample.createCriteria();
        criteria.andUnitCodeEqualTo(sysBank.getUnitCode());
        SysBankExample.Criteria criteriaTwo = sysBankExample.createCriteria();
        criteriaTwo.andUnitNameEqualTo(sysBank.getUnitName());
        sysBankExample.or(criteriaTwo);
        List<SysBank> list = sysBankMapper.selectByExample(sysBankExample);
        if (!list.isEmpty()&&list.size()>0){
            return R.error("银行/机构/支行名称或联行号系统已经录入成功，请勿重复提交！");
        }
        if (sysBank.getUnitType().equals("1")) {
            findDictionary(sysBank.getUnitBank());
        }
        sysBank.setId(UuidUtil.get32UUID());
        sysBankMapper.insert(sysBank);
        return R.ok();
    }

    @Override
    public SysBank findBankOne(String id){
        return sysBankMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateBankOne(SysBank sysBank) {
        if (sysBank.getUnitType().equals("1")) {
            findDictionary(sysBank.getUnitBank());
        }
        sysBankMapper.updateByPrimaryKeySelective(sysBank);
    }

    @Override
    public void deleteBankOne(String id) {
        sysBankMapper.deleteByPrimaryKey(id);
    }

    public  void findDictionary(String dataName){
        DictionaryExample dictionaryExample = new DictionaryExample();
        DictionaryExample.Criteria criteria = dictionaryExample.createCriteria();
        criteria.andClassCodeEqualTo("SKKHYH");
        criteria.andDataNameEqualTo(dataName);
        List<Dictionary> dictionaries = dictionaryMapper.selectByExample(dictionaryExample);
        if (dictionaries==null||dictionaries.isEmpty()){
            DictionaryExample dictionaryExampleTwo = new DictionaryExample();
            DictionaryExample.Criteria criteriaTwo = dictionaryExample.createCriteria();
            criteriaTwo.andClassCodeEqualTo("SKKHYH");
            dictionaryExampleTwo.setOrderByClause("data_order desc");
            Dictionary dictionary1 = Optional.ofNullable(dictionaryMapper.selectByExample(dictionaryExampleTwo)).orElseGet(ArrayList::new).stream().findFirst().get();
            Dictionary dictionary = new Dictionary();
            dictionary.setId(UuidUtil.get32UUID());
            dictionary.setClassCode("SKKHYH");
            dictionary.setClassName("收款开户银行");
            dictionary.setDataCode(String.valueOf(dictionary1.getDataOrder()+1));
            dictionary.setDataName(dataName);
            dictionary.setDataOrder(dictionary1.getDataOrder()+1);
            dictionary.setState("100101");
            dictionaryMapper.insert(dictionary);
        }

    }
}
